using DocumentCreationSystem.Services.AgentOps;
using DocumentCreationSystem.Models.AgentOps;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace DocumentCreationSystem.Configuration
{
    /// <summary>
    /// AgentOps服务配置 - 配置智能规划与Agentic对话联动系统
    /// </summary>
    public static class AgentOpsServiceConfiguration
    {
        /// <summary>
        /// 注册AgentOps相关服务
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddAgentOpsServices(
            this IServiceCollection services, 
            IConfiguration configuration)
        {
            // 注册核心AgentOps服务
            services.AddScoped<IAgentOpsWorkflowEngine, AgentOpsWorkflowEngine>();
            services.AddScoped<IPlanningTemplateExecutor, PlanningTemplateExecutor>();
            services.AddScoped<IAgenticDialogEnhancer, AgenticDialogEnhancer>();
            services.AddScoped<IAgentOpsMonitoringService, AgentOpsMonitoringService>();
            services.AddScoped<IAgentOpsIntegrationService, AgentOpsIntegrationService>();

            // 注册配置选项
            services.Configure<AgentOpsConfiguration>(
                configuration.GetSection("AgentOps"));

            // 注册后台服务
            services.AddHostedService<AgentOpsBackgroundService>();

            // 注册事件总线
            services.AddSingleton<IAgentOpsEventBus, AgentOpsEventBus>();

            // 注册缓存服务
            services.AddScoped<IAgentOpsCacheService, AgentOpsCacheService>();

            // 注册性能计数器
            services.AddSingleton<IAgentOpsMetricsCollector, AgentOpsMetricsCollector>();

            return services;
        }

        /// <summary>
        /// 初始化AgentOps服务
        /// </summary>
        /// <param name="serviceProvider">服务提供者</param>
        public static async Task InitializeAgentOpsAsync(IServiceProvider serviceProvider)
        {
            using var scope = serviceProvider.CreateScope();
            var integrationService = scope.ServiceProvider.GetRequiredService<IAgentOpsIntegrationService>();
            await integrationService.InitializeAsync();
        }
    }

    /// <summary>
    /// AgentOps配置选项
    /// </summary>
    public class AgentOpsConfiguration
    {
        /// <summary>
        /// 是否启用AgentOps
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 工作流引擎配置
        /// </summary>
        public WorkflowEngineConfiguration WorkflowEngine { get; set; } = new();

        /// <summary>
        /// 监控配置
        /// </summary>
        public MonitoringConfiguration Monitoring { get; set; } = new();

        /// <summary>
        /// 对话增强配置
        /// </summary>
        public DialogEnhancementConfiguration DialogEnhancement { get; set; } = new();

        /// <summary>
        /// 集成配置
        /// </summary>
        public IntegrationConfiguration Integration { get; set; } = new();
    }

    /// <summary>
    /// 工作流引擎配置
    /// </summary>
    public class WorkflowEngineConfiguration
    {
        /// <summary>
        /// 最大并发工作流数
        /// </summary>
        public int MaxConcurrentWorkflows { get; set; } = 10;

        /// <summary>
        /// 默认超时时间（分钟）
        /// </summary>
        public int DefaultTimeoutMinutes { get; set; } = 60;

        /// <summary>
        /// 是否启用自动重试
        /// </summary>
        public bool EnableAutoRetry { get; set; } = true;

        /// <summary>
        /// 最大重试次数
        /// </summary>
        public int MaxRetryAttempts { get; set; } = 3;

        /// <summary>
        /// 工作流存储路径
        /// </summary>
        public string WorkflowStoragePath { get; set; } = "Workflows";

        /// <summary>
        /// 是否启用持久化
        /// </summary>
        public bool EnablePersistence { get; set; } = true;
    }

    /// <summary>
    /// 监控配置
    /// </summary>
    public class MonitoringConfiguration
    {
        /// <summary>
        /// 是否启用监控
        /// </summary>
        public bool Enabled { get; set; } = true;

        /// <summary>
        /// 监控数据收集间隔（秒）
        /// </summary>
        public int CollectionIntervalSeconds { get; set; } = 30;

        /// <summary>
        /// 监控数据保留天数
        /// </summary>
        public int DataRetentionDays { get; set; } = 30;

        /// <summary>
        /// 是否启用性能计数器
        /// </summary>
        public bool EnablePerformanceCounters { get; set; } = true;

        /// <summary>
        /// 是否启用告警
        /// </summary>
        public bool EnableAlerts { get; set; } = true;

        /// <summary>
        /// 告警配置
        /// </summary>
        public AlertConfiguration Alerts { get; set; } = new();
    }

    /// <summary>
    /// 告警配置
    /// </summary>
    public class AlertConfiguration
    {
        /// <summary>
        /// CPU使用率告警阈值
        /// </summary>
        public double CpuUsageThreshold { get; set; } = 0.8;

        /// <summary>
        /// 内存使用率告警阈值
        /// </summary>
        public double MemoryUsageThreshold { get; set; } = 0.8;

        /// <summary>
        /// 工作流失败率告警阈值
        /// </summary>
        public double WorkflowFailureRateThreshold { get; set; } = 0.1;

        /// <summary>
        /// 响应时间告警阈值（毫秒）
        /// </summary>
        public double ResponseTimeThresholdMs { get; set; } = 5000;
    }

    /// <summary>
    /// 对话增强配置
    /// </summary>
    public class DialogEnhancementConfiguration
    {
        /// <summary>
        /// 是否启用智能建议
        /// </summary>
        public bool EnableSmartSuggestions { get; set; } = true;

        /// <summary>
        /// 是否启用上下文感知
        /// </summary>
        public bool EnableContextAwareness { get; set; } = true;

        /// <summary>
        /// 是否启用预测分析
        /// </summary>
        public bool EnablePredictiveAnalysis { get; set; } = true;

        /// <summary>
        /// 建议置信度阈值
        /// </summary>
        public double SuggestionConfidenceThreshold { get; set; } = 0.7;

        /// <summary>
        /// 最大建议数量
        /// </summary>
        public int MaxSuggestions { get; set; } = 5;

        /// <summary>
        /// 对话历史保留数量
        /// </summary>
        public int DialogHistoryLimit { get; set; } = 50;
    }

    /// <summary>
    /// 集成配置
    /// </summary>
    public class IntegrationConfiguration
    {
        /// <summary>
        /// 是否启用自动同步
        /// </summary>
        public bool EnableAutoSync { get; set; } = true;

        /// <summary>
        /// 同步间隔（秒）
        /// </summary>
        public int SyncIntervalSeconds { get; set; } = 10;

        /// <summary>
        /// 是否启用事件驱动
        /// </summary>
        public bool EnableEventDriven { get; set; } = true;

        /// <summary>
        /// 事件队列大小
        /// </summary>
        public int EventQueueSize { get; set; } = 1000;

        /// <summary>
        /// 是否启用批处理
        /// </summary>
        public bool EnableBatchProcessing { get; set; } = true;

        /// <summary>
        /// 批处理大小
        /// </summary>
        public int BatchSize { get; set; } = 10;
    }



    /// <summary>
    /// AgentOps后台服务
    /// </summary>
    public class AgentOpsBackgroundService : BackgroundService
    {
        private readonly ILogger<AgentOpsBackgroundService> _logger;
        private readonly IServiceProvider _serviceProvider;
        private readonly AgentOpsConfiguration _configuration;

        public AgentOpsBackgroundService(
            ILogger<AgentOpsBackgroundService> logger,
            IServiceProvider serviceProvider,
            IOptions<AgentOpsConfiguration> configuration)
        {
            _logger = logger;
            _serviceProvider = serviceProvider;
            _configuration = configuration.Value;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _logger.LogInformation("AgentOps后台服务已启动");

            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    using var scope = _serviceProvider.CreateScope();
                    
                    // 执行定期任务
                    await PerformPeriodicTasksAsync(scope.ServiceProvider);
                    
                    // 等待下一个周期
                    await Task.Delay(
                        TimeSpan.FromSeconds(_configuration.Monitoring.CollectionIntervalSeconds), 
                        stoppingToken);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "AgentOps后台服务执行任务时发生错误");
                }
            }

            _logger.LogInformation("AgentOps后台服务已停止");
        }

        private async Task PerformPeriodicTasksAsync(IServiceProvider serviceProvider)
        {
            // 收集监控数据
            var monitoringService = serviceProvider.GetRequiredService<IAgentOpsMonitoringService>();
            await monitoringService.GetDashboardDataAsync();

            // 清理过期数据
            await CleanupExpiredDataAsync(serviceProvider);

            // 检查系统健康状态
            await CheckSystemHealthAsync(serviceProvider);
        }

        private async Task CleanupExpiredDataAsync(IServiceProvider serviceProvider)
        {
            // 实现数据清理逻辑
            await Task.CompletedTask;
        }

        private async Task CheckSystemHealthAsync(IServiceProvider serviceProvider)
        {
            // 实现健康检查逻辑
            var monitoringService = serviceProvider.GetRequiredService<IAgentOpsMonitoringService>();
            var healthStatus = await monitoringService.GetSystemHealthAsync();
            
            if (healthStatus.OverallHealth != Models.AgentOps.HealthStatus.Healthy)
            {
                _logger.LogWarning($"系统健康状态异常: {healthStatus.OverallHealth}");
            }
        }
    }
}
